package com.sunxiansheng.user.controller;

import com.sunxiansheng.redis.util.RedisShareLockUtil;
import com.sunxiansheng.redis.util.RedisUtil;
import com.sunxiansheng.trace.TraceIdConstant;
import com.sunxiansheng.trace.TraceIdContext;
import com.sunxiansheng.user.excel.SysUserExcelExport;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.concurrent.CompletableFuture;

/**
 * Description:
 * @Author sun
 * @Create 2024/7/8 17:55
 * @Version 1.0
 */
@Slf4j
@RestController
public class TestController {

    @Resource
    private RedisShareLockUtil redisShareLockUtil;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private SysUserExcelExport sysUserExcelExport;

    @Resource
    private RedisUtil redisUtil;

    @RequestMapping("/test")
    public String test() {
        int a = 10/0;
        return "Hello World!";
    }

    @RequestMapping("/testRedis")
    public String testRedis() {
        redisTemplate.opsForValue().set("name", "sunxiansheng");
        return "Hello World!";
    }

    @RequestMapping("/testLock")
    public void testLock() {
        // 默认超时时间10s,自定义锁名字
        redisShareLockUtil.executeWithLock("mylock", () -> {
            // 需要加锁的逻辑
        });
        //
        // 自定义超时时间30s,自定义锁名字
        redisShareLockUtil.executeWithLock("mylock", 30, () -> {
            // 需要加锁的逻辑
        });
    }


    @RequestMapping("/testDate")
    public void testDate(@RequestBody MyDate myDate) {
        System.out.println(myDate);
    }

    @Data
    static class MyDate {
        private LocalDateTime dateTime;
        private LocalDate date;
        private LocalTime time;
    }


    @RequestMapping("/testExcel")
    public void testExcel() {
        sysUserExcelExport.exportExcel();
    }

    @RequestMapping("/testLog")
    public void testLog() {
        // 打印日志
        log.info("test log");
        // 异步打印日志（需要手动的将traceId传递到子线程）
        for (int i = 0; i < 10; i++) {
            CompletableFuture.runAsync(
                    () -> {
                        // 从上下文中获取traceId
                        String traceId = TraceIdContext.getTraceId();
                        // 放到子线程的MDC中
                        MDC.put(TraceIdConstant.TRACE_ID, traceId);
                        log.info("test log async");
                    }
            );
        }
    }


}